package com.cby.third.sample

import android.os.Bundle
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

/**
 * @description: WebActivity
 *
 * @author ChenBaoyang
 * @date 2021/10/26 09:45
 */
class WebActivity : AppCompatActivity() {

    private lateinit var mWebView: WebView
    private lateinit var logTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web)

        mWebView = findViewById<View>(R.id.webview) as WebView
        // 启用javascript
        mWebView.settings.javaScriptEnabled = true
        // 从assets目录下面的加载html
        mWebView.loadUrl("file:///android_asset/wx.html")
        mWebView.addJavascriptInterface(this, "wx")
        logTextView = findViewById<View>(R.id.text) as TextView
        val button = findViewById<View>(R.id.button) as Button
        button.setOnClickListener { // 无参数调用
            mWebView.loadUrl("javascript:actionFromNative()")
            // 传递参数调用
            mWebView.loadUrl("javascript:actionFromNativeWithParam(" + "'come from Native'" + ")")
        }
    }


    @JavascriptInterface
    fun actionFromJs() {
        runOnUiThread {
            Toast.makeText(this@WebActivity, "js调用了Native函数", Toast.LENGTH_SHORT).show()
            val text = """
            ${logTextView.text}
            js调用了Native函数
            """.trimIndent()
            logTextView.text = text
        }
    }

    @JavascriptInterface
    fun actionFromJsWithParam(str: String) {
        runOnUiThread {
            Toast.makeText(this@WebActivity, "js调用了Native函数传递参数：$str", Toast.LENGTH_SHORT).show()
            val text = """
            ${logTextView.text}
            js调用了Native函数传递参数：$str
            """.trimIndent()
            logTextView.text = text
        }
    }
}